<template>
  <div class="autocomplete">
    <nut-input
        v-model="inputValue"
        clearable
        @input="onInput"
        @focus="onFocus"
        @blur="onBlur"
        @keydown.down="onArrowDown"
        @keydown.up="onArrowUp"
        @keydown.enter="onEnter"
        :placeholder="placeholder"
        @clear="clear"
    />
    <ul v-if="isOpen" class="suggestions">
      <li
          v-for="(item, index) in filteredItems"
          :key="item"
          :class="{ active: index === activeIndex }"
          @mousedown="selectItem(item)"
      >
        {{ item.name }}
      </li>
    </ul>
  </div>
</template>

<script setup>
import {ref, computed, watch} from 'vue';
import tool from "@/utils/tool.js";

const props = defineProps({
  placeholder: {type: String,default: ''},
  cat: {type: String,default: ''},
});

const emit = defineEmits(['select']);

const inputValue = defineModel();
const isOpen = ref(false);
const activeIndex = ref(-1);

const filteredItems = ref([])
const getList = (queryString) => {
  tool.post('common/dropdown',{cat: props.cat,keyWord: queryString}).then(ret => {
    if(ret.stat) {
      filteredItems.value = ret.data
    }
  })
}
watch(() => inputValue.value, (newVal) => {
  getList(newVal)
})
const onInput = () => {
  isOpen.value = true;
  activeIndex.value = -1;
};

const onFocus = () => {
  isOpen.value = true;
  getList('')
};

const onBlur = () => {
  setTimeout(() => {
    isOpen.value = false;
  }, 200);
};

const onArrowDown = () => {
  if (activeIndex.value < filteredItems.value.length - 1) {
    activeIndex.value++;
  }
};

const onArrowUp = () => {
  if (activeIndex.value > 0) {
    activeIndex.value--;
  }
};

const onEnter = () => {
  if (activeIndex.value >= 0) {
    selectItem(filteredItems.value[activeIndex.value]);
  }
};

const clear = () => {
  inputValue.value = ''
}

const selectItem = (item) => {
  inputValue.value = item.name;
  isOpen.value = false;
  emit('select', item);
};

</script>

<style scoped>
.autocomplete {
  position: relative;
  display: inline-block;
}

input {
  padding: 8px;
  font-size: 16px;
  border: 1px solid #ccc;
  border-radius: 4px;
}

.suggestions {
  position: absolute;
  border: 1px solid #ccc;
  border-top: none;
  z-index: 1000;
  width: 100%;
  max-height: 200px;
  overflow-y: auto;
  background-color: #E4E7ED;
  list-style-type: none;
  padding: 0;
  margin: 0;
}

.suggestions li {
  padding: 8px;
  cursor: pointer;
}

.suggestions li.active {
  background-color: #f0f0f0;
}

.suggestions li:hover {
  background-color: #f0f0f0;
}
</style>